package edu.nf.relaxenjoy.service.impl;

import edu.nf.relaxenjoy.service.MinioService;
import io.minio.MinioClient;
import io.minio.ObjectWriteResponse;
import io.minio.PutObjectArgs;
import io.minio.RemoveObjectArgs;
import lombok.RequiredArgsConstructor;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @author zhu
 * @date 2024-12-18
 */
@Service
@RequiredArgsConstructor
public class MinioServiceImpl implements MinioService {

    private final MinioClient minioClient;

    @Override
    public String uploadFile(MultipartFile file) {
        try {
            String fileName = file.getOriginalFilename();
            InputStream inputStream = file.getInputStream();
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            fileName = uuid + fileName;
            String datePath = new DateTime().toString("yyyy/MM/dd");
            fileName = datePath + fileName;
            minioClient.putObject(
                    PutObjectArgs.builder()
                            .bucket("myapp")
                            .object(fileName)
                            .stream(inputStream, file.getSize(), -1)
                            .contentType(file.getContentType())
                            .build());

            return "http://127.0.0.1:9000/myapp/" + fileName;
        } catch (Exception e) {
            throw new RuntimeException("上传文件失败");
        }
    }

    @Override
    public List<String> uploadFiles(Integer num, MultipartRequest request) {
        List<MultipartFile> files = new ArrayList<>();
        List<String> paths = new ArrayList<>();
        if (num > 0) {
            for (int i = 0; i < num; i++) {
                files.add(request.getFile("images" + i));
            }
            for (MultipartFile file : files) {
                String path = uploadFile(file);
                paths.add(path);
            }
        }
        return paths;
    }

    @Override
    public void deleteFile(String fileName) {
        try {
            String replaceFileName = fileName.replace("http://127.0.0.1:9000/myapp/", "");
            minioClient.removeObject(
                    RemoveObjectArgs.builder()
                            .bucket("myapp")
                            .object(replaceFileName)
                            .build());
        } catch (Exception e) {
            throw new RuntimeException("删除文件失败");
        }
    }

    @Override
    public void deleteFiles(List<String> fileNames) {
        try {
            for (String fileName : fileNames) {
                deleteFile(fileName);
            }
        } catch (Exception e) {
            throw new RuntimeException("批量删除文件失败");
        }
    }
}
